import { Component, OnInit } from '@angular/core';
import { ActivatedRoute} from '@angular/router';
import { Product, ProductService, Comment } from '../shared/product.service';
@Component({
  selector: 'app-product-detail',
  templateUrl: './product-detail.component.html',
  styleUrls: ['./product-detail.component.css']
})
export class ProductDetailComponent implements OnInit {
  product: Product;
  comments: Comment[];
  newRating: number = 5;
  newComment: string = "";
  isCommentHidden: boolean = true;
  constructor(private routeInfo: ActivatedRoute,
              private productService: ProductService
  ) { 

  }

  ngOnInit() {
    let productId = parseInt(this.routeInfo.snapshot.params["productId"]);
    this.product = this.productService.getProduct(productId);
    this.comments = this.productService.getCommentsForProductId(productId);
  }
  addComment() {
    let date = new Date();
    let d = date.getFullYear() + '-' + date.getMonth() * 1 + 1 + "-" + date.getDate();
    let comment = new Comment(0, this.product.id, d, "游客", this.newRating, this.newComment);
    this.comments.unshift(comment);
    //添加评论后重新计算当前商品的星级
    let sum = this.comments.reduce((sum, comment) => sum + comment.rating, 0);
    this.product.rating = sum / this.comments.length;
    //重置表单，隐藏发表评论区
    this.newComment = "";
    this.newRating = 5;
    this.isCommentHidden = true;
  }

}
